<template>
  <!-- 绑定手机 -->
  <view class="">
    <view class="flex pd input">
      <text class="mr">+86</text>
      <input type="number" placeholder="手机号" v-model="phone" />
    </view>

    <view class="flex pd input" style="position: relative">
      <input
        type="number"
        placeholder="请输入验证码"
        v-model="code"
        @input="inputCode"
      />
      <button
        class="code"
        @click="codeClick"
        :disabled="iscode"
        :class="iscode ? 'bg-main-disabled' : ''"
        style="color: #fff"
      >
        {{ codeTime }}
      </button>
    </view>
    <view class="pd">
      <button
        class="mainBg"
        style="border-radius: 200rpx; color: #fff"
        :disabled="disabled"
        :class="disabled ? 'bg-main-disabled' : ''"
        type="number"
        @click="submit"
      >
        绑定
      </button>
    </view>
  </view>
</template>

<script>
import { bindphone, sendcode } from "@/api/api";
export default {
  data() {
    return {
      phone: "13245685211",
      code: "",
      disabled: true,
      codeTime: "获取验证码",
      iscode: false,
    };
  },
  methods: {
    //   手机号匹配规则
    check() {
      var rule = /^1[34578]\d{9}$/;
      if (!rule.test(this.phone)) {
        uni.showToast({
          title: "手机号格式不正确",
          icon: "none",
        });
        return false;
      }
      return true;
    },
    async codeClick() {
      if (this.check()) {
        this.codeTime = 60;
        this.iscode = true;
        let timer = setInterval(() => {
          if (this.codeTime === 1) {
            this.codeTime = "获取验证码";
            this.iscode = false;
            clearInterval(timer);
            return;
          }
          this.codeTime--;
        }, 1000);
        let code = await sendcode(this.phone);
        uni.showToast({
          icon: "none",
          title: `验证码为${code.msg}`,
        });
      }
    },
    async submit() {
      let res = await bindphone({
        phone: this.phone,
        code: this.code,
      });
      console.log(res);
      if (res.statusCode === 400) {
        uni.showToast({
          icon: "none",
          title: res.data.msg,
        });
      } else {
        uni.showToast({
          title: "绑定成功",
          icon: "none",
        });
        this.$store.commit("edituser", { key: "phone", value: this.phone });
        setTimeout(() => {
          uni.navigateBack({});
        }, 100);
      }
    },
    inputCode() {
      if (this.check() && this.code.length !== 0) {
        this.disabled = false;
      } else {
        this.disabled = true;
      }
    },
  },
};
</script>

<style>
.input {
  border-bottom: 1px solid #cfd1d5;
  padding-top: 20rpx;
  padding-bottom: 20rpx;
  margin-bottom: 30rpx;
}
.mr {
  margin-right: 30rpx;
}
.code {
  width: 180rpx;
  background-color: #ff4a6a;
  color: #fff;
  font-size: 24rpx;
  position: absolute;
  right: 0;
  bottom: 0;
}
</style>
